package cn.iocoder.yudao.module.trade.service.delivery;

import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.module.trade.controller.admin.delivery.vo.sf.SfChannelReqVO;
import cn.iocoder.yudao.module.trade.controller.admin.delivery.vo.sf.SfCreateReqVO;
import cn.iocoder.yudao.module.trade.controller.admin.delivery.vo.sf.SfPrintReqVO;
import cn.iocoder.yudao.module.trade.framework.delivery.core.client.convert.SfExpressConvert;
import cn.iocoder.yudao.module.trade.framework.delivery.core.client.dto.sfexpress.SfPrintWaybillsDTO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sf.csim.express.service.CallExpressServiceTools;
import com.sf.csim.express.service.HttpClientUtil;
import com.sf.csim.express.service.code.ExpressServiceCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
@Validated
public class SfExpressServiceImpl implements SfExpressService {

    /**
     * 丰桥新沙箱测试顾客编码  Yg4Zf06w_sxZs3A5D
     * 校验码  3Xdk1jqeG1Xod9nUXus8Op7DNOkchTnw
     **/
    private static final String CLIENT_CODE = "YQXXKGEFBMK1";  //此处替换为您在丰桥平台获取的顾客编码
    private static final String CHECK_WORD = "DhG7LEZmEQWin9tfinW0b2W4KDHGd651";//此处替换为您在丰桥平台获取的校验码


    //沙箱环境的地址 -PRO
    private static final String CALL_URL_BOX = "https://sfapi-sbox.sf-express.com/std/service";

    @Override
    public JSONObject expressCreateOrder(SfCreateReqVO reqVO) throws UnsupportedEncodingException {
        ExpressServiceCodeEnum standardService = ExpressServiceCodeEnum.EXP_RECE_CREATE_ORDER;
        CallExpressServiceTools tools = CallExpressServiceTools.getInstance();
        Map<String, String> params = new HashMap<String, String>();
        String timeStamp = String.valueOf(System.currentTimeMillis());
        params.put("partnerID", CLIENT_CODE);  // 顾客编码 ，对应丰桥上获取的clientCode
        params.put("requestID", UUID.randomUUID().toString().replace("-", ""));
        params.put("serviceCode", standardService.getCode());// 接口服务码
        params.put("timestamp", timeStamp);
        String msgData = JsonUtils.toJsonString(reqVO);
        params.put("msgData", msgData);
        params.put("msgDigest", tools.getMsgDigest(msgData, timeStamp, CHECK_WORD));
        String result = HttpClientUtil.post(CALL_URL_BOX, params);
        log.info("创建订单msgData:{}",msgData);
        JSONObject resultData = null;
//        String result = "{\"apiErrorMsg\":\"\",\"apiResponseID\":\"00018DCFA494833FD2228C6160C7083F\",\"apiResultCode\":\"A1000\",\"apiResultData\":\"{\\\"success\\\":true,\\\"errorCode\\\":\\\"S0000\\\",\\\"errorMsg\\\":null,\\\"msgData\\\":{\\\"orderId\\\":\\\"o202401311500061-0\\\",\\\"originCode\\\":\\\"\\\",\\\"destCode\\\":null,\\\"filterResult\\\":2,\\\"remark\\\":\\\"\\\",\\\"url\\\":null,\\\"paymentLink\\\":null,\\\"isUpstairs\\\":null,\\\"isSpecialWarehouseService\\\":null,\\\"mappingMark\\\":null,\\\"agentMailno\\\":null,\\\"returnExtraInfoList\\\":null,\\\"waybillNoInfoList\\\":[{\\\"waybillType\\\":1,\\\"waybillNo\\\":\\\"SF7444478636221\\\",\\\"boxNo\\\":null,\\\"length\\\":null,\\\"width\\\":null,\\\"height\\\":null,\\\"weight\\\":null,\\\"volume\\\":null},{\\\"waybillType\\\":1,\\\"waybillNo\\\":\\\"SF7444478633794\\\",\\\"boxNo\\\":null,\\\"length\\\":null,\\\"width\\\":null,\\\"height\\\":null,\\\"weight\\\":null,\\\"volume\\\":null}],\\\"routeLabelInfo\\\":[{\\\"code\\\":\\\"1000\\\",\\\"routeLabelData\\\":{\\\"waybillNo\\\":\\\"SF7444478633794\\\",\\\"sourceTransferCode\\\":null,\\\"sourceCityCode\\\":\\\"\\\",\\\"sourceDeptCode\\\":null,\\\"sourceTeamCode\\\":null,\\\"destCityCode\\\":null,\\\"destDeptCode\\\":null,\\\"destDeptCodeMapping\\\":null,\\\"destTeamCode\\\":null,\\\"destTeamCodeMapping\\\":null,\\\"destTransferCode\\\":null,\\\"destRouteLabel\\\":null,\\\"proName\\\":null,\\\"cargoTypeCode\\\":\\\"C201\\\",\\\"limitTypeCode\\\":\\\"T4\\\",\\\"expressTypeCode\\\":\\\"B1\\\",\\\"codingMapping\\\":null,\\\"codingMappingOut\\\":null,\\\"xbFlag\\\":null,\\\"printFlag\\\":null,\\\"twoDimensionCode\\\":\\\"MMM={'k1':null,'k2':null,'k3':'','k4':'T4','k5':'SF7444478636221','k6':'','k7':''}\\\",\\\"proCode\\\":\\\"T4\\\",\\\"printIcon\\\":null,\\\"abFlag\\\":null,\\\"destPortCode\\\":null,\\\"destCountry\\\":null,\\\"destPostCode\\\":null,\\\"goodsValueTotal\\\":null,\\\"currencySymbol\\\":null,\\\"cusBatch\\\":null,\\\"goodsNumber\\\":null,\\\"errMsg\\\":null,\\\"checkCode\\\":null,\\\"proIcon\\\":null,\\\"fileIcon\\\":null,\\\"fbaIcon\\\":null,\\\"icsmIcon\\\":null,\\\"destGisDeptCode\\\":null,\\\"newIcon\\\":null,\\\"sendAreaCode\\\":null,\\\"destinationStationCode\\\":null,\\\"sxLabelDestCode\\\":null,\\\"sxDestTransferCode\\\":null,\\\"sxCompany\\\":null,\\\"newAbFlag\\\":null,\\\"destAddrKeyWord\\\":null,\\\"rongType\\\":null,\\\"waybillIconList\\\":null},\\\"message\\\":null}],\\\"contactInfoList\\\":null,\\\"sendStartTm\\\":null,\\\"customerRights\\\":null,\\\"expressTypeId\\\":null}}\"}";
        log.info("result:{}", result);
        if (StringUtils.isNotBlank(result)) {
            JSONObject resultObj = JSON.parseObject(result);
            if (StringUtils.isNotEmpty(resultObj.getString("apiResultData"))) {
                resultData = JSON.parseObject(resultObj.getString("apiResultData"));
                if (!resultData.getBoolean("success")) {
                    log.info("顺丰-创建订单异常:{}", resultData.getString("errorMsg"));
                }
            }
        }
        return resultData;
    }

    @Override
    public JSONObject printWaybills(SfPrintReqVO reqVO) throws UnsupportedEncodingException {
        ExpressServiceCodeEnum standardService = ExpressServiceCodeEnum.COM_RECE_CLOUD_PRINT_WAYBILLS;
        CallExpressServiceTools tools = CallExpressServiceTools.getInstance();
        Map<String, String> params = new HashMap<String, String>();
        String timeStamp = String.valueOf(System.currentTimeMillis());
        params.put("partnerID", CLIENT_CODE);  // 顾客编码 ，对应丰桥上获取的clientCode
        params.put("requestID", UUID.randomUUID().toString().replace("-", ""));
        params.put("serviceCode", standardService.getCode());// 接口服务码
        params.put("timestamp", timeStamp);

        SfPrintWaybillsDTO dto = SfExpressConvert.INSTANCE.convert(reqVO);
        log.info("dto:{}",dto);
        dto.setVersion("2.0"); //版本号，传固定值:2.0
        dto.setFileType("pdf"); //pdf格式
        dto.setSync(true); //true: 同步,false: 异步,默认异步
        dto.getExtJson().setEncryptFlag("1100");//数据脱敏 收件人寄件人姓名脱敏 地址不脱敏
        String msgData = JsonUtils.toJsonString(dto);
        params.put("msgData", msgData);
        params.put("msgDigest", tools.getMsgDigest(msgData, timeStamp, CHECK_WORD));

        log.info("输入的msgData:{}", msgData);

        String result = HttpClientUtil.post(CALL_URL_BOX, params);
//        String result = "{\"apiResponseID\":\"00018DC4611A123FE1743B58CA25B33F\",\"apiErrorMsg\":\"\",\"apiResultCode\":\"A1000\",\"apiResultData\":\"{\\\"obj\\\":{\\\"clientCode\\\":\\\"YQXXKGEFBMK1\\\",\\\"fileType\\\":\\\"pdf\\\",\\\"files\\\":[{\\\"areaNo\\\":1,\\\"documentSize\\\":0,\\\"pageCount\\\":0,\\\"pageNo\\\":1,\\\"seqNo\\\":1,\\\"token\\\":\\\"AUTH_tkv12_f146d1855480549d262b5c46ab0ab597ff20a97d9d0db45c16bedeb4fabd112b012deadd477ee524b1d690ce01baa3cdffbb125a6ccf69b73778dba2eb5157eb81d412d36a9ddd1fa6fbd8bb7159e6161ca7e91a98ae6247d3505225a8e2ad7e2241190743e236586c380a0dc9df2542f3de740e21153da9a54567d9887e63c99b236a4ab7bbd612f799bf8fab48dd72578d22f451f292582a49fc0fd1a04a2eccf04c06594b2d1435bafc84d194dcba29bf6de4dc3a38badee815ff495b82a4\\\",\\\"url\\\":\\\"https://eos-scp-core-shenzhen-futian1-oss.sf-express.com:443/v1.2/AUTH_EOS-SCP-CORE/print-file-sbox/AAABjcRhGoLkchdwIz1OqorMK_Pl18A8_SF7444478373607_fm_150_standard_YQXXKGEFBMK1_1_1.pdf\\\",\\\"waybillNo\\\":\\\"SF7444478373607\\\"}],\\\"templateCode\\\":\\\"fm_150_standard_YQXXKGEFBMK1\\\"},\\\"requestId\\\":\\\"b458a10f803c482f9d9dae906eb33da5\\\",\\\"success\\\":true}\"}";
        if (StringUtils.isNotBlank(result)) {
            JSONObject resultObj = JSON.parseObject(result);
            log.info("面单打印返回结果:{}", resultObj);
            if (!resultObj.getJSONObject("apiResultData").getBoolean("success")) {
                log.info("顺丰-打印面单异常:{}", resultObj.getJSONObject("apiResultData").getString("apiErrorMsg"));
                return resultObj.getJSONObject("apiResultData");
            }
//            return resultObj.getJSONObject("apiResultData").getJSONObject("obj").getJSONArray("files");
            return resultObj.getJSONObject("apiResultData");
        }
        return null;
    }

    @Override
    public JSONObject channelExpressOrder(SfChannelReqVO reqVO) throws UnsupportedEncodingException {
        ExpressServiceCodeEnum standardService = ExpressServiceCodeEnum.EXP_RECE_UPDATE_ORDER;
        CallExpressServiceTools tools = CallExpressServiceTools.getInstance();
        Map<String, String> params = new HashMap<String, String>();
        String timeStamp = String.valueOf(System.currentTimeMillis());
        params.put("partnerID", CLIENT_CODE);  // 顾客编码 ，对应丰桥上获取的clientCode
        params.put("requestID", UUID.randomUUID().toString().replace("-", ""));
        params.put("serviceCode", standardService.getCode());// 接口服务码
        params.put("timestamp", timeStamp);

        reqVO.setDealType(2); //客户订单操作标识: 1:确认 (丰桥下订单接口默认自动确认，不需客户重复确认，该操作用在其它非自动确认的场景) 2:取消
        String msgData = JsonUtils.toJsonString(reqVO);
        log.info("取消订单msgData:{}",msgData);
        params.put("msgData", msgData);
        params.put("msgDigest", tools.getMsgDigest(msgData, timeStamp, CHECK_WORD));
        String result = HttpClientUtil.post(CALL_URL_BOX, params);
        if (StringUtils.isNotBlank(result)) {
            JSONObject resultObj = JSON.parseObject(result);
            log.info("取消订单返回结果:{}", resultObj);
            if (!resultObj.getJSONObject("apiResultData").getBoolean("success")) {
                log.info("顺丰-取消订单异常:{}", resultObj.getJSONObject("apiResultData").getString("apiErrorMsg"));
                return resultObj.getJSONObject("apiResultData");
            }
//            return resultObj.getJSONObject("apiResultData").getJSONObject("obj").getJSONArray("files");
            return resultObj.getJSONObject("apiResultData");
        }
        return null;
    }
}
